package ch15;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

public class Example15_7 {
    public static void main(String args[]) {
        WindowWord win=new WindowWord();
        win.setTitle("英-汉小字典");
    }
}

class WindowWord extends JFrame {
    JTextField inputText,showText;
    WordPolice police;           //监视器
    WindowWord() {
        setLayout(new FlowLayout());
        inputText=new JTextField(6);
        showText=new JTextField(6);
        add(inputText);
        add(showText);
        police=new WordPolice();
        police.setJTextField(showText);
        inputText.addActionListener(police);
        setBounds(100,100,400,280);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class WordPolice implements ActionListener {
    JTextField showText;
    HashMap<String,String> hashtable;
    File file=new File("word.txt");
    Scanner sc=null;
    WordPolice() {
        hashtable=new HashMap<String,String>();
        try{ sc=new Scanner(file);
            while(sc.hasNext()){
                String englishWord=sc.next();
                String chineseWord=sc.next();
                hashtable.put(englishWord,chineseWord);
            }
        }
        catch(Exception e){}
    }
    public void setJTextField(JTextField showText) {
        this.showText=showText;
    }
    public void actionPerformed(ActionEvent e) {
        String englishWord=e.getActionCommand();
        if(hashtable.containsKey(englishWord)) {
            String chineseWord=hashtable.get(englishWord);
            showText.setText(chineseWord);
        }
        else {
            showText.setText("没有此单词");
        }
    }
}